// pages/home/home.js
const app = getApp();
import request from "../../utils/request";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    cartCount: 0,
    token: "",
    loginCode: "",
    phoneCode: "",
    userPhoneNumber: "",
    userdata: {
      avatar: "https://jiazhiqin.oss-cn-chengdu.aliyuncs.com/mini-program/commen/commen/commen/userProfile.png",
    },
    headerImgUrl: "",
    showchangeNmage: false,
    changeName: "",
    showchangesex: false,
    pitchon:
      "width: 40vw;background-color: #fff;color: #111;margin-top: 50rpx;",
    unpitchon:
      "width: 40vw;background-color: #fff;color: #111;margin-top: 50rpx;",
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.login();
    this.getuser();
  },
  async changesexman() {
    if (this.data.userdata.sex == 1) {
    } else {
      try {
        const res = await request({
          url: app.globalData.baseURL + "/app-user-api/member/user/update",
          method: "PUT",
          data: { sex: 1 },
        });
        if (res.code == 0) {
          this.setData({
            pitchon:
              "width: 40vw;background-color: #111;color: #fff;margin-top: 50rpx;",
            unpitchon:
              "width: 40vw;background-color: #fff;color: #111;margin-top: 50rpx;",
          });
          this.getuser();
        }
      } catch {
        console.log();
      }
    }
  },
  async changesexwoman() {
    if (this.data.userdata.sex == 0) {
      console.log(1);
    } else {
      try {
        const res = await request({
          url: app.globalData.baseURL + "/app-user-api/member/user/update",
          method: "PUT",
          data: { sex: 0 },
        });
        if (res.code == 0) {
          this.setData({
            pitchon:
              "width: 40vw;background-color: #fff;color: #111;margin-top: 50rpx;",
            unpitchon:
              "width: 40vw;background-color: #fff;color: #111;margin-top: 50rpx;",
          });
          this.getuser();
        }
      } catch {
        console.log();
      }
    }
  },
  getchangesex() {
    this.setData({
      showchangesex: true,
    });
  },
  onClosechangesex() {
    this.setData({
      showchangesex: false,
    });
  },
  changePhoneNumber() {
    wx.navigateTo({
      url: `/pages/phoneNumberLogin/phoneNumberLogin?title=${"修改手机号"}`,
    });
  },
  onChooseAvatar(event) {
    console.log(event.detail);
    const token = wx.getStorageSync("token");
    let imageUrl = event.detail.avatarUrl;
    if (event.detail.avatarUrl !== "") {
      wx.uploadFile({
        filePath: imageUrl,
        url: app.globalData.baseURL + "/app-user-api/member/user/update-avatar",
        header: {
          "Authorization": token ? `Bearer ${token}` : "",
          "Content-Type": "multipart/form-data",
          "tenant-id": 156,
          "login_user_type":3
        },
        name: "avatarFile",
        success: (res) => {
          const headerPortrait = JSON.parse(res.data);
          const portrait = headerPortrait.data;
          this.changePortrait(portrait);
        },
      });
    }
  },
  async changePortrait(portrait) {
    try {
      const res = await request({
        url: app.globalData.baseURL + "/app-user-api/member/user/update",
        method: "PUT",
        data: { "avatar": portrait },
      });
      if (res.code == 0) {
        this.getuser();
      }
    } catch (error) {
      console.log("error");
    }
  },
  async getuser() {
    try {
      const res = await request({
        url: app.globalData.baseURL + "/app-user-api/member/user/get",
        method: "GET",
      });
      if (res.data.sex == 1) {
        this.setData({
          pitchon:
            "width: 40vw;background-color: #111;color: #fff;margin-top: 50rpx;",
        });
      } else if (res.data.sex == 0) {
        this.setData({
          unpitchon:
            "width: 40vw;background-color: #111;color: #fff;margin-top: 50rpx;",
        });
      }
      this.setData({
        userdata: res.data,
      });
    } catch (error) {
      console.error("请求发生错误：", error);
    }
  },
  getPhoneLogin() {
    wx.navigateTo({
      url: "/pages/phoneNumberLogin/phoneNumberLogin",
    });
  },
  getchangename() {
    this.setData({
      showchangeNmage: true,
    });
  },
  onClosechangename() {
    this.setData({
      showchangeNmage: false,
    });
  },
  changenameblur(e) {
    this.setData({
      changeName: e.detail.value,
    });
  },
  async getUserName() {
    try {
      const res = await request({
        url: app.globalData.baseURL + "/app-user-api/member/user/update",
        method: "PUT",
        data: { nickname: this.data.changeName },
      });
      if (res.code == 0) {
        this.getuser();
        wx.showToast({
          title: "修改昵称成功",
          icon: "success",
        });
        this.setData({
          showchangeNmage: false,
        });
      }
    } catch {
      console.log(e);
    }
  },
  goback() {
    wx.navigateBack({
      delta: 1,
    });
  },
  login() {
    wx.login({
      success: (res) =>
        this.setData({
          loginCode: res.code,
        }),
    });
  },
  updateCartBadge() {
    const app = getApp();
    const newCount = app.globalData.cartCount;
    wx.setStorageSync("cartCount", newCount); // 存储到本地存储，以便跨页面访问
    this.setData({ cartCount: newCount });
  },
  getPhone(e) {
    console.log(e.detail.code);
    this.setData({
      phoneCode: e.detail.code,
    });
    this.getPhoneNumber();
  },
  getPhoneNumber() {
    const app = getApp();
    wx.request({
      url:
        app.globalData.baseURL +
        "/app-user-api/member/auth/weixin-mini-app-login",
      method: "POST",
      header: {
        "tenant-id": "156",
        "login_user_type":3,
        "Authorization": "Bearer test1",
      },
      data: {
        phoneCode: this.data.phoneCode,
        loginCode: this.data.loginCode,
        state: "9b2ffbc1-7425-4155-9894-9d5c08541d61",
      },
      success: (res) => {
        console.log("res", res);
        const token = res.data.data.accessToken;
        wx.setStorageSync("token", token);
        wx.setStorageSync("expiresTime", res.data.data.expiresTime);
        wx.setStorageSync("refreshToken", res.data.data.refreshToken);
        wx.setStorageSync("userId", res.data.data.userId);
      },
    });
  },
  async quitLogin() {
    const app = getApp();
    wx.showModal({
      title: "提示",
      content: "您确定要退出系统吗",
      success: (res) => {
        if (res.confirm) {
          this.logout(app);
        } else if (res.cancel) {
          wx.showToast({
            title: "取消退出",
            icon: "error",
          });
        }
      },
    });
  },

  async logout(app) {
    try {
      const response = await request({
        url: app.globalData.baseURL + "/app-user-api/member/auth/logout",
        method: "POST",
      });

      if (response.code === 0) {
        wx.clearStorageSync();
        wx.showToast({
          title: "退出登录成功",
          icon: "success",
        });
        wx.switchTab({
          url: "/pages/index/index",
        });
      } else {
        wx.showToast({
          title: "退出登录失败",
          icon: "none",
        });
      }
    } catch (error) {
      // 网络请求失败的处理
      console.error("退出登录请求失败：", error);
      wx.showToast({
        title: "请求失败，请重试",
        icon: "none",
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.updateCartBadge();
    this.getuser();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    return {
      title: "嘉之勤官网小程序",
      path: "/pages/index/index",
      imageUrl:
        "https://youyougo2.oss-cn-chengdu.aliyuncs.com/0201506f6fc0f4145e34159c2e2ac66b94b96450dd29e5a19d177edc5dad8023.png",
    };
  },
});
